package com.example.cyh.bczapp.Code.Helper;

import java.io.IOException;
import java.util.Dictionary;
import java.util.Enumeration;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by cyh on 2017/5/5.
 */

public class HttpHelper {
    /**
     * @param url   请求的地址
     * @param param 键值对参数
     * @return
     * @throws IOException
     */
    public static String POST(String url, Dictionary<String, String> param) throws IOException {
        OkHttpClient client = new OkHttpClient();
        //请求参数设置
        FormBody.Builder body = new FormBody.Builder();
        if (param != null) {
            for (Enumeration key = param.keys(); key.hasMoreElements(); ) {//便利dic取出键值添加参数
                String k = key.nextElement().toString();
                body.add(k, param.get(k)).build();
            }
        }
        RequestBody rb = body.build();
        //请求构造器
        Request request = new Request.Builder().url(url).post(rb).build();
        //响应
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return "网络错误";
        }
    }
    public static String Get(String url, Dictionary<String, String> param) throws IOException {
        OkHttpClient client = new OkHttpClient();
        //请求参数设置
        FormBody.Builder body = new FormBody.Builder();
        int i=1;
        if (param != null) {
            for (Enumeration key = param.keys(); key.hasMoreElements(); ) {//便利dic取出键值添加参数
                String k = key.nextElement().toString();
                url+=(i==1?"?":"&")+k+"="+param.get(k);
                i++;
            }
        }
        //请求构造器
        Request request = new Request.Builder().url(url).get().build();
        //响应
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return "网络错误";
        }
    }
}
